import * as actionType from '../actions/actionType'
const initState={
    list:JSON.parse(window.localStorage.getItem('Yue-cart'))||[]
};
const syncCartStorage=(cartList)=>{
    window.localStorage.setItem('Yue-cart',JSON.stringify((cartList)))
};
export default (state=initState,action)=>{
    switch (action.type) {
        case actionType.CART_COUNT_ADD:
            const newAddList=state.list.map(item=>{
                if(item.id===action.id){
                    item.count=item.count+1;
                }
                return item
            });
            syncCartStorage(newAddList);
            return Object.assign({},state,{
                list:newAddList
            });
        case actionType.CART_COUNT_REDUCE:
            const newReduceList=state.list.reduce((result,item)=>{
                if(item.id===action.id){
                        item.count=item.count-1;
                }
                if(item.count>0) {
                    result.push(item)
                }
                return result;
            },[]);
            syncCartStorage(newReduceList);
            return Object.assign({},state,{
                list:newReduceList
            });
        case actionType.ADD_TO_CART:
            const { cartItem }=action;
            const isInCartList=state.list.some(item=>item.id===cartItem.id);
            if(isInCartList){
                const newAddList=state.list.map(item=>{
                    if(item.id===cartItem.id){
                        item.count=item.count+1;
                    }
                    return item
                });
                syncCartStorage(newAddList);
                return Object.assign({},state,{
                    list:newAddList
                });
            }else{
                cartItem.count=1;
                cartItem.img=cartItem.imgs[0].img;
                cartItem.checkinfo='黑色';
                syncCartStorage(state.list.concat(cartItem));
                return Object.assign({},state,{
                    list:state.list.concat(cartItem)
            })
            }
        default:return state;
    }
}


